package com.sxpi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxpi.common.result.Result;
import com.sxpi.convert.CouponsConvert;
import com.sxpi.mapper.CouponsItemMapper;
import com.sxpi.mapper.CouponsMapper;
import com.sxpi.model.entity.Coupons;
import com.sxpi.model.entity.CouponsItem;
import com.sxpi.model.page.PageResult;
import com.sxpi.model.vo.CouponsVo;
import com.sxpi.service.CouponsService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author happy
 * @create 2024-10-29-{TIME}
 */
@Service
@Slf4j
public class CouponsServiceImpl extends ServiceImpl<CouponsMapper, Coupons> implements CouponsService {

    @Resource
    private CouponsMapper couponsMapper;

    @Resource
    private CouponsItemMapper couponsItemMapper;

    @Resource
    private CouponsConvert couponsConvert;

    @Override
    public Result<List<Coupons>> getValidCoupons() {

        return null;
    }

    /**
     * @param pageNo
     * @param pageSize
     * @param id
     * @return
     */

    @Override
    public Result<PageResult<Coupons>> getAllCoupons(Integer pageNo, Integer pageSize, Long id) {
        Page<Coupons> couponsPage = new Page<>(pageNo, pageSize);

        //根据条件查询
        LambdaQueryWrapper<Coupons> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!Objects.isNull(id), Coupons::getId, id);

        Page<Coupons> couponsPage1 = couponsMapper.selectPage(couponsPage, wrapper);

        List<Coupons> records = couponsPage1.getRecords();

        PageResult<Coupons> resultPageResult = new PageResult<>();
        resultPageResult.setPageNo(pageNo);
        resultPageResult.setPageSize(pageSize);
        resultPageResult.setResult(records);
        resultPageResult.setTotal((int) couponsPage1.getTotal());


        return Result.ok(resultPageResult);
    }

    /**
     * 新增优惠券模板
     *
     * @param coupons
     * @return
     */
    @Override
    @Transactional
    public Result<Boolean> addCoupons(Coupons coupons, Integer count) {
        int insert = 0;
        for (int i = 0; i < count; i++) {
            Coupons newCoupon = new Coupons();
            BeanUtils.copyProperties(coupons, newCoupon); // 复制其他属性
            newCoupon.setCode(UUID.randomUUID().toString()); // 生成唯一的优惠码
            insert += couponsMapper.insert(newCoupon);
        }
        return Result.ok(insert > 0);
    }

    @Override
    @Transactional
    public Result<List<CouponsVo>> getAllCouponsByUser(Long userId, Integer pageNo, Integer pageSize, Integer status) {

        //根据用户id查询优惠券
        LambdaQueryWrapper<CouponsItem> eq = new LambdaQueryWrapper<CouponsItem>().eq(CouponsItem::getUserId, userId);
        List<CouponsItem> couponsItems = couponsItemMapper.selectList(eq);

        //判断优惠券是否过期
        couponsItems.forEach(item -> {
            if (item.getEndTime().isBefore(LocalDateTime.now())) {
                 LambdaUpdateWrapper<Coupons> set = new LambdaUpdateWrapper<Coupons>().eq(Coupons::getId, item.getCouponsId()).set(Coupons::getStatus, 3);
                couponsMapper.update(new Coupons(), set);
            }
        });

        //获取要查询的所有id
        List<Long> couponsIds = couponsItems.stream().map(CouponsItem::getCouponsId).toList();

        List<Coupons> coupons1 = new ArrayList<>();
        couponsIds.forEach(id -> {
//             LambdaQueryWrapper<Coupons> wrapper = new LambdaQueryWrapper<>();
//             wrapper.eq(Coupons::getId, id);
//             wrapper.eq(Coupons::getStatus, status);
            final LambdaQueryWrapper<Coupons> eq1 = new LambdaQueryWrapper<Coupons>().eq(Coupons::getId, id).eq(Coupons::getStatus, status);
            Coupons coupons = couponsMapper.selectOne(eq1);
             if(coupons==null){
                 return;
             }
             coupons1.add(coupons);
        });

        List<CouponsVo> couponsVos = CouponsConvert.INSTANCE.convertEntityToVo(coupons1);
        couponsVos.forEach(item -> {
            CouponsItem couponsItem = couponsItemMapper.selectOne(new LambdaQueryWrapper<CouponsItem>().eq(CouponsItem::getCouponsId, item.getId()));
            if (couponsItem==null){
                return;
            }
            item.setStartTime(couponsItem.getStartTime());
            item.setEndTime(couponsItem.getEndTime());
            item.setUserId(couponsItem.getUserId());

        });

        return Result.ok(couponsVos);
    }

    @Override
    @Transactional
    public Result<Boolean> exchangeCoupons(String data, Long userId) {
        LambdaQueryWrapper<Coupons> eq = new LambdaQueryWrapper<Coupons>().eq(Coupons::getCode, data);
        Coupons coupons = couponsMapper.selectOne(eq);

        if (Objects.isNull(coupons)) {
            return Result.build(false, 201, "优惠券不存在");
        }

        //修改优惠券状态
         LambdaUpdateWrapper<Coupons> set = new LambdaUpdateWrapper<Coupons>().eq(Coupons::getId, coupons.getId()).set(Coupons::getStatus, 1);
         int update = couponsMapper.update(new Coupons(), set);

        int insert= 0;
        if (update > 0 && coupons.getStatus() == 0) {
              CouponsItem couponsItem = new CouponsItem();
              couponsItem.setCouponsId(coupons.getId());
              couponsItem.setUserId(userId);
              couponsItem.setStartTime(LocalDateTime.now());
              LocalDateTime now = LocalDateTime.now(); // 获取当前的日期和时间
              LocalDateTime afterDays = now.plusDays(coupons.getTimeEffect()); // 当前时间加上 30 天
              couponsItem.setEndTime(afterDays);
              insert = couponsItemMapper.insert(couponsItem);
         }else {
            return Result.build(false, 201, "优惠券已经使用");
        }

        return Result.ok(insert>0);
    }
}